# -*- coding: utf-8 -*-
import sys

sys.path.append("../..")
from db.mysql import MysqlClient
import requests
from common.helper import Helper
from common.config import *
import json
from itertools import product
from threading import Thread
class Spider(object):
    def __init__(self):
        self.name = "i自由交通工具意外伤害保险"
        self.mysql = MysqlClient()
    def genProductInfo(self):
        plan = {
            # 保障天数
            "days": ["1y", "6m", "3m"],
            # 保险人数
            "people_count": ["NaN"],
            # 民航意外伤残/死亡
            "airplane_death": ["1000000", "1500000", "2000000", "2500000", "3000000"],
            # 轮船意外伤残/死亡
            "ship_death": ["0", "1"],
            # 火车意外伤残/死亡
            "train_death": ["0", "1"],
            # 动车组意外伤残/死亡
            "motor_death": ["0", "1"],
            # 地铁意外伤残/死亡
            "subway_death": ["0", "1"],
            # 市内公共汽车伤残/死亡
            "bus_death": ["0", "1"],
            # 出租意外车伤残/死亡
            "taxi_death": ["0", "1"],
            # 长途汽车意外伤残/死亡
            "passenger_death": ["0", "1"],
            # 旅行社客车伤残/死亡
            "travel_death": ["0", "1"],
            # 私家车意外伤残/死亡
            "private_death": ["0", "1"],
            # 公务车意外伤残/死亡
            "service_death": ["0", "1"]
        }

        for v in product(plan["days"], plan["people_count"], plan["airplane_death"], plan["ship_death"],
                         plan["train_death"], plan["motor_death"], plan["subway_death"], plan["bus_death"],
                         plan["taxi_death"], plan["passenger_death"], plan["travel_death"], plan["private_death"],
                         plan["service_death"]):
            data = Helper.formatProductInfo(plan, v)

            if data["airplane_death"] == "1000000":
                for k, v in data.items():
                    if v == "1":
                        data[k] = "100000"
                    elif v == "0":
                        data[k] = "0"
                self.mysql.cursor.execute(domain[self.name]["insert_sql"].format(**data))
                self.mysql._conn.commit()
                print(domain[self.name]["insert_sql"].format(**data))

            elif data["airplane_death"] == "1500000":
                for k, v in data.items():
                    if v == "1":
                        data[k] = "200000"
                    elif v == "0":
                        data[k] = "0"
                self.mysql.cursor.execute(domain[self.name]["insert_sql"].format(**data))
                self.mysql._conn.commit()
                print(domain[self.name]["insert_sql"].format(**data))

            elif data["airplane_death"] == "2000000":
                for k, v in data.items():
                    if v == "1":
                        data[k] = "300000"
                    elif v == "0":
                        data[k] = "0"
                self.mysql.cursor.execute(domain[self.name]["insert_sql"].format(**data))
                self.mysql._conn.commit()
                print(domain[self.name]["insert_sql"].format(**data))

            elif data["airplane_death"] == "2500000":
                for k, v in data.items():
                    if v == "1":
                        data[k] = "400000"
                        data["private_death"] = "300000"
                        data["service_death"] = "300000"
                    elif v == "0":
                        data[k] = "0"
                self.mysql.cursor.execute(domain[self.name]["insert_sql"].format(**data))
                self.mysql._conn.commit()
                print(domain[self.name]["insert_sql"].format(**data))
            else:
                for k, v in data.items():
                    if v == "1":
                        data[k] = "500000"
                        data["private_death"] = "300000"
                        data["service_death"] = "300000"
                    elif v == "0":
                        data[k] = "0"
                self.mysql.cursor.execute(domain[self.name]["insert_sql"].format(**data))
                self.mysql._conn.commit()
                print(domain[self.name]["insert_sql"].format(**data))
    # 执行爬虫
    def requestJson(self, dt=None, mysql=None):
        data = []
        if dt["days"] == "1y":
            period = "1"
        elif dt["days"] == "6m":
            period = "2"
        else:
            period = "3"
        if dt["airplane_death"] != "0":
            item = {"sex": "M", "birthday": "1989-04-25", "coveredType": "2", "coveredYears": "1", "recommendCode": "",
                    "payingType": "2", "payingYears": "1", "payFrequency": period, "cbsProductId": 1000003,
                    "amount": dt["airplane_death"],
                    "countWay": "1", "productDutyDesc": "民航"}
            data.append(item)
        if dt["ship_death"] != "0":
            item = {"sex": "M", "birthday": "1989-04-25", "coveredType": "2", "coveredYears": "1", "recommendCode": "",
                    "payingType": "2", "payingYears": "1", "payFrequency": period, "cbsProductId": 1000026,
                    "amount": dt["ship_death"],
                    "countWay": "1", "productDutyDesc": "轮船"}
            data.append(item)
        if dt["train_death"] != "0":
            item = {"sex": "M", "birthday": "1989-04-25", "coveredType": "2", "coveredYears": "1", "recommendCode": "",
                    "payingType": "2", "payingYears": "1", "payFrequency": period, "cbsProductId": 1000012,
                    "amount": dt["train_death"],
                    "countWay": "1", "productDutyDesc": "火车"}

            data.append(item)
        if dt["motor_death"] != "0":
            item = {"sex": "M", "birthday": "1989-04-25", "coveredType": "2", "coveredYears": "1", "recommendCode": "",
                    "payingType": "2", "payingYears": "1", "payFrequency": period, "cbsProductId": 1000013,
                    "amount": dt["motor_death"],
                    "countWay": "1", "productDutyDesc": "动车组列车（国内）"}
            data.append(item)
        if dt["subway_death"] != "0":
            item = {"sex": "M", "birthday": "1989-04-25", "coveredType": "2", "coveredYears": "1", "recommendCode": "",
                    "payingType": "2", "payingYears": "1", "payFrequency": period, "cbsProductId": 1000014,
                    "amount": dt["subway_death"],
                    "countWay": "1", "productDutyDesc": "地铁"}
            data.append(item)
        if dt["bus_death"] != "0":
            item = {"sex": "M", "birthday": "1989-04-25", "coveredType": "2", "coveredYears": "1", "recommendCode": "",
                    "payingType": "2", "payingYears": "1", "payFrequency": period, "cbsProductId": 1000015,
                    "amount": dt["bus_death"],
                    "countWay": "1", "productDutyDesc": "市内公共汽、电车"}
            data.append(item)
        if dt["taxi_death"] != "0":
            item = {"sex": "M", "birthday": "1989-04-25", "coveredType": "2", "coveredYears": "1", "recommendCode": "",
                    "payingType": "2", "payingYears": "1", "payFrequency": period, "cbsProductId": 1000017,
                    "amount": dt["taxi_death"],
                    "countWay": "1", "productDutyDesc": "出租车"}
            data.append(item)
        if dt["passenger_death"] != "0":
            item = {"sex": "M", "birthday": "1989-04-25", "coveredType": "2", "coveredYears": "1", "recommendCode": "",
                    "payingType": "2", "payingYears": "1", "payFrequency": period, "cbsProductId": 1000018,
                    "amount": dt["passenger_death"],
                    "countWay": "1", "productDutyDesc": "长途公共汽车"}
            data.append(item)
        if dt["travel_death"] != "0":
            item = {"sex": "M", "birthday": "1989-04-25", "coveredType": "2", "coveredYears": "1", "recommendCode": "",
                    "payingType": "2", "payingYears": "1", "payFrequency": period, "cbsProductId": 1000019,
                    "amount": dt["travel_death"],
                    "countWay": "1", "productDutyDesc": "旅行社客车、机场公共汽车"}
            data.append(item)
        if dt["private_death"] != "0":
            item = {"sex": "M", "birthday": "1989-04-25", "coveredType": "2", "coveredYears": "1", "recommendCode": "",
                    "payingType": "2", "payingYears": "1", "payFrequency": period, "cbsProductId": 1000020,
                    "amount": dt["private_death"],
                    "countWay": "1", "productDutyDesc": "私有汽车"}
            data.append(item)
        if dt["service_death"] != "0":
            item = {"sex": "M", "birthday": "1989-04-25", "coveredType": "2", "coveredYears": "1", "recommendCode": "",
                    "payingType": "2", "payingYears": "1", "payFrequency": period, "cbsProductId": 1000021,
                    "amount": dt["service_death"],
                    "countWay": "1", "productDutyDesc": "公务车"}
            data.append(item)
        payload = json.dumps(data)
        r = requests.post(url=domain[self.name]["url"], headers=domain[self.name]["header"], data=payload)
        if r.status_code == 200 and r.json()["success"]:
            price = Helper.decimalParse(sum([price["premium"] for price in r.json()["data"]]))
            data = {
                "name":self.name,
                "id":dt["id"],
                "price":price
            }
            print( data )
            mysql.updatePrice( data )
        else:
            data = {
                "name":self.name,
                "id":dt["id"],
                "state":3
            }
            mysql.updateTask( data )
            print("\n/*产品价格更新失败:%d*/"%dt["id"])
    def startProcess(self):
        for i in range(5):
            mysql = MysqlClient()
            t = Thread(target=Helper.runProcess, args=(mysql, self.name, self.requestJson))
            t.start()
if __name__ == '__main__':
    s = Spider()
    s.startProcess()
